﻿using System;
using System.Collections.Generic;
using System.Text;
using QD.Utill;
using QD.Snapshot.Core.Config;
using System.Windows.Forms;
using System.Threading;
using NSoup.Nodes;
using System.Text.RegularExpressions;
using NSoup.Select;
using System.Data;
using System.Net;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.IO;

namespace QD.Snapshot.Core.BLL
{
    public class Search_360 : SearchBase
    {
        static string HSPK = "";
        static string QiHooGUID = "";
        static int dbCount = 0;     //数据库查询次数
        static bool IsFristRun = true;     //首次运行获取对面的cookie

        public Search_360(TextBox textBox, int SleepTime)
        {
            this.textBox = textBox;
            this.SleepTime = SleepTime;
            this.copyform = "1";        //360搜索引擎
            Echo("360截图已启动");
        }

        HttpRequest Http = new HttpRequest("Mozilla/5.0 (compatible;Windows NT 6.1; WOW64;Trident/6.0;MSIE 9.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.27 Safari/537.36"
            , "https://www.so.com/");
        Model.TaskModel_360 taskModel = new Model.TaskModel_360();
        string htmls, msg;
        public override void Search(string keyword, Model.Product product, Model.WebSite company)
        {
            htmls = string.Empty;

            Thread.Sleep(SleepTime);

            InitToken();
            Http.ClearCookie();
            Http.AddCookie("HSPK", HSPK, "www.so.com", DateTime.Now.AddYears(1));
            Http.AddCookie("QiHooGUID", QiHooGUID, "www.so.com", DateTime.Now.AddYears(1));

            msg = Http.Requset(string.Format(Engine.URL_360, keyword), out htmls);

            IsCode_360 = CheckCode(htmls);   //是否出现验证码

            if (msg.Length > 0)
            {
                Echo(string.Format("搜索 {0} 返回错误", keyword));
            }
            else if (IsCode_360)
            {
                EchoCodeLog(EngineType._360, "360出现验证码");
                Thread.Sleep(1000);
            }
            else
            {
                Echo(string.Format("搜索 {0}", keyword));
            }
            taskModel.itemid = product.itemid;
            taskModel.keyword = keyword;
            taskModel.company = company;
            taskModel.html = htmls;

            NumHelper.Instance.SetNum360(1);    //统计搜索速度
            ThreadPool.QueueUserWorkItem(new WaitCallback(CheckOrAdd), taskModel);
        }

        void CheckOrAdd(object obj)
        {
            Model.TaskModel_360 model = obj as Model.TaskModel_360;

            CheckOrAdd(model.html, model.keyword, model.itemid, model.company);
        }
        
        void CheckOrAdd(string html, string keyword, int itemid, Model.WebSite company)
        {
            NSoup.Nodes.Document doc = NSoup.NSoupClient.Parse(html);
            Regex r1 = new Regex(FixRegex(company.ShortName), RegexOptions.IgnoreCase);
            Regex r2 = new Regex(FixRegex(keyword), RegexOptions.IgnoreCase);
            Regex SiteName = new Regex(FixRegex(company.SiteName), RegexOptions.IgnoreCase);
            Regex Cellphone = new Regex(FixRegex(company.Cellphone), RegexOptions.IgnoreCase);
            Regex phone = new Regex(FixRegex(company.Phone), RegexOptions.IgnoreCase);

            CheckOrAdd(doc, r1, SiteName, Cellphone, phone, itemid, company.UserID, keyword);
        }

        private readonly object obj = new object();
        Model.Snap snapModel = new Model.Snap();
        void CheckOrAdd(Document doc, Regex r1, Regex SiteName, Regex Cellphone, Regex phone, int itemid, int userid, string keyword, int page = 1)
        {
            Elements result = doc.GetElementsByClass("result");
            if (result == null || result.IsEmpty) return;
            Element parent = result[0];
            if (parent == null) return;

            NSoup.Select.Elements list = parent.GetElementsByClass("res-list");

            HideElement(doc.GetElementById("side"));                        //隐藏右侧
            HideElement(doc.GetElementById("m-spread-left"));               //隐藏顶部广告
            HideElement(doc.GetElementById("e_idea_pp"));                   //隐藏顶部广告
            HideElement(doc.GetElementById("m-spread-bottom"));             //隐藏底部广告            
            HideElement(doc.GetElementById("mohe-biu_3c_general"));         //隐藏3C产品推荐
            HideElement(doc.GetElementById("rs"));                          //隐藏相关搜索
            HideElement(doc.GetElementById("mohe-map_new_catering_ip"));    //隐藏地图
            HideElement(doc.GetElementById("mohe-biu_ali_b2b"));            //隐藏B2B推荐
            HideElement(doc.GetElementById("mohe-etao_shangye"));           //隐藏淘宝推荐
            HideElement(doc.GetElementById("mohe-biu_3c_general_yesky"));   //隐藏3C推荐
            HideElement(doc.GetElementById("mohe-video_story-single"));     //隐藏视频推荐
            HideElement(doc.GetElementById("mohe-map_new_singleC_default-level_three"));    //隐藏360地图

            HideElementList(parent.GetElementsByClass("pics"));          //去掉每行 左边图片
            HideElementList(parent.GetElementsByClass("res-comm-img"));  //去掉每行 左边图片

            if (doc.GetElementById("mohe-360pic") != null)
                HideElement(doc.GetElementById("mohe-360pic").Parent);              //隐藏360的图片频道

            if (doc.GetElementById("mohe-360pic_strong") != null)
                HideElement(doc.GetElementById("mohe-360pic_strong").Parent);      //隐藏360的图片频道

            if (doc.GetElementById("mohe-svideo") != null)
                HideElement(doc.GetElementById("mohe-svideo").Parent);              //隐藏360的视频频道

            if (parent.GetElementById("mohe-map_new_singleC_default-level_two") != null)    //隐藏360地图
                HideElement(doc.GetElementById("mohe-map_new_singleC_default-level_two").Parent);

            Elements txtList = parent.GetElementsByClass("res-comm-con");
            if (txtList != null)
            {
                foreach (Element ele in txtList)    //填充左边的图片位置
                    ele.Attributes["style"] = "width:100%";
            }

            int index = 0;
            bool isFirst = true;
            foreach (Element ele in list)
            {
                index++;
                if (r1.IsMatch(ele.Text()) || CheckShortNameList(ele.Text()) || CheckQJY(ele.Text(), SiteName, Cellphone, phone))
                {
                    string index_key = GetMd5(ele.GetElementsByTag("h3").Text); //第几行的key,更新时，用来确定更新哪一行
                    string platform = GetPlatform(ele.Html());    //上词的平台

                    if (isFirst)
                    {
                        RemoveAttr(result);
                        isFirst = false;
                    }

                    //添加成功记录
                    lock (obj)
                    {
                        snapModel.itemid = itemid;
                        snapModel.userid = userid;
                        snapModel.keyword = keyword;
                        snapModel.ranking = index;
                        snapModel.copyform = Convert.ToInt32(copyform);
                        snapModel.page = page;
                        snapModel.state = 0;
                        snapModel.clientid = SiteConfig.ClientId;
                        snapModel.platform = platform;
                        snapModel.updatetime = DateTime.Now;
                        snapModel.index_key = index_key;
                        snapModel.html = result.Html();
                        AddSnap(snapModel);
                        BLL.File.Snap.AddSnap(snapModel);
                    }
                }
            }
        }

        protected override void RemoveAttr(Elements result)
        {
            Elements ele = result.Select("a");
            ele.Attr("href", "#");
            ele.RemoveAttr("target");
            ele.RemoveAttr("rel");
            ele.RemoveAttr("data-url");
            ele.RemoveAttr("data-res");
            ele.RemoveAttr("data-tp");
            ele.RemoveAttr("data-cache");
            ele.RemoveAttr("data-h");
            ele.RemoveAttr("data-k");
            ele.RemoveAttr("data-type");
            ele.RemoveAttr("data-i");

            Elements script = result.Select("script");
            script.Remove();
        }
        
        void InitToken()
        {
            if (!IsFristRun)
            {
                if (!IsCode_360) return;    //未出现验证码
            }

            IsFristRun = false;
            //出现验证码，获取最新的 HSPK 和 QiHooGUID
            try
            {
                BLL.SnapToken.GetBySo(HSPK);
                Dictionary<string, object>  dic = BLL.SnapToken.GetBySo();
                if (dic != null)
                {
                    HSPK = Convert.ToString(dic["HSPK"]);
                    QiHooGUID = Convert.ToString(dic["QiHooGUID"]);
                }
            }
            catch { }

            //记录次数
            dbCount++;
            if (dbCount >= 10)
            {
                Pigeon.Utility.Log.Write(string.Format("code{0}.log", DateTime.Now.ToString("yyyyMMdd")), string.Format("360从数据库中拉取参数{0}次！", dbCount));
                dbCount = 0;
            }
        }
    }
}